import React from 'react';
import moment from 'moment';
import { Form, Select, DatePicker, Button, message, TreeSelect } from 'antd';
import { mapConfig } from 'Constants/mapConstants';
import { connect } from 'react-redux';
import Api from 'Utils/api';
import './index.scss';

const FormItem = Form.Item;
const TreeNode = TreeSelect.TreeNode;
const Option = Select.Option;
const dateFormat = 'YYYY-MM-DD';
/*const data = [
  {
    id: 3,
    title: 'C局',
    longitude: 120.7406902313,
    latitude: 28.8516277595,
    normal_image: 'images/track/icon_business_monitor.png',
    light_image: 'images/track/icon_business_monitor.png',
  }
];*/
class TrackPage extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      zoom: 16, //地图级别,
      selectId: '',
      treeData: [],
      peopleInfo: [],
      trackData: []
    };
    this.onLoad = ::this.onLoad;
    this.renderDepartmentTreeNode = ::this.renderDepartmentTreeNode;
    this.renderTreeNode = ::this.renderTreeNode;
    this.onChangeDepartment = ::this.onChangeDepartment;
  }
  componentDidMount() {
    this.initRenderTreeData();
    //经纬度地图显示；
    this.map = new T.Map('mapContent');
    //双击放大地图；
    this.map.enableDoubleClickZoom();
    //地图滚轮缩放；
    this.map.enableScrollWheelZoom();
    //地图惯性拖拽；
    this.map.enableInertia();
    //先清除地图覆盖物，在显示
    // this.map.clearOverLays();
    //创建比例尺控件对象
    const scale = new T.Control.Scale();
    //添加比例尺控件
    this.map.addControl(scale);
    //设置显示地图的中心点和级别
    this.map.centerAndZoom(new T.LngLat(mapConfig.longitude, mapConfig.latitude), 16);
    this.onLoad();
  }
  componentWillReceiveProps() {
    this.map.checkResize();
  }
  onLoad() {
    this.map.clearOverLays();
    const data = this.state.trackData;
    if (data.length === 0) {
      return;
    }
    const dataIemArr = data.map(item => new T.LngLat(item.longitude, item.latitude));
    const res = this.map.getViewport(dataIemArr);
    console.log('zoom', res.zoom);
    this.map.panTo(new T.LngLat(res.center.lng, res.center.lat), res.zoom);
    //创建线对象
    this.line = new T.Polyline(dataIemArr);
    //向地图上添加线
    this.map.addOverLay(this.line);
    this.line.setColor('#2f46ff');
    this.line.setOpacity(1);
    const start = new T.Marker(new T.LngLat(data[0].longitude, data[0].latitude),
      { icon: new T.Icon({
        iconUrl: 'images/track/icon_addr.png',
        iconSize: new T.Point(15, 18),
        iconAnchor: new T.Point(7, 18)
      }) });
    this.map.addOverLay(start);
  }

  // 机构
  initRenderTreeData() {
    const api = new Api({
      method: 'GET',
      path: '/depts/admin',
      success: (json) => {
        console.log(json);
        this.setState({
          treeData: json,
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  renderDepartmentTreeNode() {
    return this.state.treeData.map((tree) => {
      return this.renderTreeNode(tree);
    });
  }
  renderTreeNode(item) {
    if (!item.sub_depts) {
      return (
        <TreeNode value={item.id.toString()} title={item.name} key={item.id} />
      );
    }
    if (item.sub_depts.length === 0) {
      return (
        <TreeNode value={item.id.toString()} title={item.name} key={item.id} />
      );
    }
    return (
      <TreeNode value={item.id.toString()} title={item.name} key={item.id}>
        {
          item.sub_depts.map((child) => {
            return this.renderTreeNode(child);
          })
        }
      </TreeNode>
    );
  }
  onChangeDepartment(value) {
    const self = this;
    const deptId = parseInt(value, 10);
    const api = new Api({
      method: 'GET',
      path: `/justices/staff/${deptId}`,
      success: (res) => {
        self.setState({
          peopleInfo: res
        });
        this.props.form.setFieldsValue({ id: undefined });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  handleClick() {
    this.props.form.validateFieldsAndScroll((err) => {
      if (!err) {
        const formValue = this.props.form.getFieldsValue();
        const api = new Api({
          method: 'GET',
          path: `/depts/trace/${parseInt(formValue.id, 10)}`,
          query: {
            result_time: moment(formValue.result_time.hours(0).minutes(0).seconds(0)).format(dateFormat)
          },
          success: (res) => {
            this.setState({
              trackData: res
            }, () => {
              if (res.length === 0) {
                message.warn('该执法人员没有执法轨迹');
              } else {
                this.onLoad();
              }
            });
            console.log(res);
          },
          error: (msg) => {
            message.error(msg);
          }
        });
        api.run();
      }
    });
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const { treeData, peopleInfo } = this.state;
    return (
      <div className="track-page">
        <div className="search-action-wrap">
          <Form layout="inline">
            <div className="label">
              选择所属机构：
            </div>
            <FormItem>
              {getFieldDecorator('type', {
                rules: [
                  { required: true, message: '请选择' }
                ]
              })(
                <TreeSelect
                  style={{ width: 260 }}
                //  value={Treevalue}
                  dropdownStyle={{ maxHeight: 300, overflow: 'auto' }}
                  //  treeData={treeData}
                  placeholder="请选择"
                  onChange={this.onChangeDepartment}
                >
                  {
                    treeData.length > 0 ? this.renderDepartmentTreeNode() : ''
                  }
                </TreeSelect>
              )}
            </FormItem>
            <div className="label">
              选择执法人员：
            </div>
            <FormItem>
              {getFieldDecorator('id', {
                rules: [
                  { required: true, message: '请选择' }
                ]
              })(
                <Select style={{ width: 260 }} placeholder="请选择" >
                  {
                    peopleInfo && peopleInfo.length > 0 ?
                      peopleInfo.map(item => (
                        <Option value={item.id.toString()} key={item.id} >{item.name}</Option>
                      ))
                      : ''
                  }
                </Select>
              )}
            </FormItem>
            <div className="label">
              选择时间：
            </div>
            <FormItem>
              {getFieldDecorator('result_time', {
                rules: [
                  { required: true, message: '请选择' }
                ]
              })(
                <DatePicker placeholder="请选择" />
              )}
            </FormItem>
            <Button type="primary" className="search-btn" onClick={this.handleClick.bind(this)}>
              <img src="images/icon_search.png" alt="查询" />
             查询
            </Button>
          </Form>
        </div>
        <div className="map-border-bg">
          <div className="map-wrap" id="mapContent" />
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing,
    ...state.mapReducer
  };
}

export default connect(mapStateToProps)(Form.create()(TrackPage));

